import RootSiblingsManager from 'react-native-root-siblings';
import type { OpenDialogOptions, OpenDialogWrapperRefs } from './types';
import OpenDialogWrapper from './wrapper';

export const openDialog = (options: OpenDialogOptions) => {
  const {
    content,
    onClose,
    canClose,
    ...props
  } = options;
  
  let ref: OpenDialogWrapperRefs | null = null;
  let root: RootSiblingsManager | null = null;

  const closeDialog = () => {
    onClose?.();
    root?.destroy();
    root = null;
  }

  root = new RootSiblingsManager(
    <OpenDialogWrapper
      {...props}
      ref={e => ref = e}
      children={content}
      afterClose={closeDialog}
      canClose={options.canClose}
    />
  );

  return () => ref?.close();
}